package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.SoilMoistureContentDao;
import edu.ynu.se.xiecheng.achitectureclass.dto.DataDTO;
import edu.ynu.se.xiecheng.achitectureclass.entity.AirTemperature;
import edu.ynu.se.xiecheng.achitectureclass.entity.CarbonDioxide;
import edu.ynu.se.xiecheng.achitectureclass.entity.Device;
import edu.ynu.se.xiecheng.achitectureclass.entity.SoilMoistureContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SoilMoistureContentService extends LogicService<SoilMoistureContentDao, SoilMoistureContent, Long> {
    public SoilMoistureContentService(@Autowired SoilMoistureContentDao dao) { super(dao);}

    @Transactional
    public void SaveData(String name, Double Data, Device device) {
        SoilMoistureContent soilMoistureContent = new SoilMoistureContent();
        soilMoistureContent.setName(name);
        soilMoistureContent.setData(Data);
        soilMoistureContent.setDevice(device);
        dao.save(soilMoistureContent);
    }
    @Transactional
    public Double getLatestData() {
        List<SoilMoistureContent> soilMoistureContents = dao.findAll(Sort.by(Sort.Direction.DESC, "id"));
        SoilMoistureContent latest = soilMoistureContents.get(0);
        return latest.getData();
    }

    @Transactional
    public List<DataDTO> get7Data() {
        List<SoilMoistureContent> allSoilMoistureContents = dao.findAll(Sort.by(Sort.Direction.DESC, "id"));
        List<DataDTO> dataDTOS = new ArrayList<>();
        List<SoilMoistureContent> soilMoistureContents = new ArrayList<>(allSoilMoistureContents.subList(0, Math.min(allSoilMoistureContents.size(), 7)));
        for (SoilMoistureContent soilMoistureContent : soilMoistureContents) {
            DataDTO dataDTO = new DataDTO();
            dataDTO.setData(soilMoistureContent.getData());
            dataDTO.setGetTime(soilMoistureContent.getCreateTime());
            dataDTOS.add(dataDTO);
        }
        return dataDTOS;
    }
}
